package distributed.entity;

import java.util.Collection;
import java.util.Hashtable;
import java.util.UUID;

import distributed.controller.DataBaseController;

/**
 * Singleton model for holding and hashing all of the events that the server will be managing
 * @author Michal Talmor
 *
 */
public class EventModel {
	/** The singleton instance of this class */
	static EventModel instance;
	
	/** A hash of the event ID's with their associated events */
	Hashtable<String, Event> events = new Hashtable<String, Event>();
	
	/**
	 * @param eventID string, the ID of the event that is being searched for.
	 * @return eventID string, returns the event with the inputted ID
	 */
	public Event getEvent(String eventID) {
		if (events.get(eventID) == null) {
			try {
				return DataBaseController.getInstance().retrieveEvent(eventID);
			} catch (Exception e) {
				return null;
			}
		}
		else 
			return events.get(eventID);
	}
	
	/**
	 * @param numChoices integer, the number of choices in a round.
	 * @param numRounds integer, the number of rounds in the game.
	 * @param question String, the question of the event.
	 * @param isOpen boolean, is the event open?
	 * @return id String, returns the ID of the created event.
	 */
	public String createEvent(int numChoices, int numRounds,
			String question, boolean isOpen) {
		String id = UUID.randomUUID().toString().substring(24);
		events.put(id, new Event(numChoices, numRounds, question, isOpen));
		return id;
	}
	
	/**
	 * @return instance EventModel, returns a new EventModel.
	 */
	public static EventModel getInstance() {
		if (instance == null)
			instance = new EventModel();
		return instance;
	}
	
	/**
	 * @return evens.keySet() Collection<String> returns the ids
	 */
	public Collection<String> getEventIDs() {
		return events.keySet();
	}
	
	/**
	 * @param id String, removse an event based on its ID.
	 */
	public void removeEvent(String id) {
		events.remove(id);
		try {
			DataBaseController.getInstance().deleteEvent(id);
		} catch (Exception e) {}
	}

}
